package ms.pms.service;

import com.github.pagehelper.PageHelper;
import ms.common.exception.BizException;
import ms.common.page.Page;
import ms.common.util.bean.BeanUtil;
import ms.common.util.string.StringUtil;
import ms.pms.bean.CommonQueryParamBean;
import ms.pms.bean.PermissionParamBean;
import ms.pms.bean.RoleParamBean;
import ms.pms.config.ResponseCode;
import ms.pms.dao.PermissionDAO;
import ms.pms.dao.RolePermissionDAO;
import ms.pms.entity.Permission;
import ms.pms.entity.Role;
import ms.pms.entity.RolePermission;
import ms.pms.vo.PermissionVO;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Isolation;
import org.springframework.transaction.annotation.Transactional;

import java.util.ArrayList;
import java.util.List;
import java.util.Map;

/**
 * Project Name: ms
 * File Name: PermissionService
 * Package Name: ms.pms.service
 * Date: 2018/6/21  16:46
 * Copyright (c) 2018, tianyul All Rights Reserved.
 */
@Service
public class PermissionService {

    @Autowired
    private PermissionDAO permissionDAO;

    @Autowired
    private RolePermissionDAO rolePermissionDAO;

    /**
     * 查询权限信息
     * @param commonQueryParamBean
     * @return
     */
    public Page<Permission> query(CommonQueryParamBean commonQueryParamBean) {
        com.github.pagehelper.Page page = PageHelper.startPage(commonQueryParamBean.getPageNo(), commonQueryParamBean.getPageSize());
        List<Permission> permissions = permissionDAO.query(commonQueryParamBean.getStatus(), commonQueryParamBean.getName());
        return new Page(page.getPageNum(), page.getPageSize(), (int)page.getTotal(), permissions);
    }

    /**
     * 权限列表
     * @param commonQueryParamBean
     * @return
     */
    public List<PermissionVO> list(CommonQueryParamBean commonQueryParamBean) {
        //返回结果
        List<PermissionVO> permissionVOS = new ArrayList<>();
        //权限id集合
        List<Long> rolePermissionIds = new ArrayList<>();
        //查询角色对应权限
        RolePermission rolePermissionParam = new RolePermission();
        rolePermissionParam.setRoleId(commonQueryParamBean.getOptId());
        List<RolePermission> rolePermissions = rolePermissionDAO.select(rolePermissionParam);

        if(!StringUtil.isEmpty(rolePermissions)) {
            rolePermissions.forEach(rolePermission -> {
                rolePermissionIds.add(rolePermission.getPermissionId());
            });
        }

        //目前菜单最多2级，权限最多3级
        Permission pidParam = new Permission();
        pidParam.setPid(0L);
        //父菜单
        List<Permission> permissions = permissionDAO.select(pidParam);
        for (Permission permission : permissions) {
            //拷贝权限
//            PermissionVO permissionVO = BeanUtil.copy(permission, PermissionVO.class);
//            List<PermissionVO> permissionVOList = new ArrayList<>();
            pidParam.setPid(permission.getId());

            //2级菜单
            List<Permission> secondPermissions = permissionDAO.select(pidParam);
            for (Permission p: secondPermissions) {
                p.setStatus(rolePermissionIds.contains(p.getId())?10:1);
                PermissionVO pvo = BeanUtil.copy(p, PermissionVO.class);
                List<PermissionVO> pList = new ArrayList<>();
                pidParam.setPid(p.getId());
                //按钮
                List<Permission> thirdPermissions = permissionDAO.select(pidParam);
                for (Permission pms : thirdPermissions) {
                    pms.setStatus(rolePermissionIds.contains(pms.getId())?10:1);
                    pms.setUrl(null);
                    pList.add(BeanUtil.copy(pms, PermissionVO.class));
                }
                pvo.setChildren(pList);
//                permissionVOList.add(pvo);
                permissionVOS.add(pvo);
            }

//            permissionVO.setChildren(permissionVOList);
//            permissionVOS.add(permissionVO);
        }

        return permissionVOS;
    }

    /**
     * 保存权限信息
     * @param permissionParamBean
     */
    @Transactional(rollbackFor = {Exception.class}, isolation = Isolation.READ_COMMITTED)
    public void save(PermissionParamBean permissionParamBean) {
        Long id = permissionParamBean.getId();
        //查询权限是否存在
        Permission permission = permissionDAO.selectByPrimaryKey(id);
        if(StringUtil.isEmpty(permission)) {//新增
            Permission param = BeanUtil.copy(permissionParamBean, Permission.class);
            param.setCreateTime(System.currentTimeMillis());

            permissionDAO.insert(param);
            return;
        }
        //修改
        permission.setName(permissionParamBean.getName());

        permissionDAO.updateByPrimaryKey(permission);
    }

    /**
     * 启用
     * @param id
     */
    @Transactional(rollbackFor = {Exception.class}, isolation = Isolation.READ_COMMITTED)
    public void use(Long id) {
        //查询权限是否存在
        Permission permission = permissionDAO.selectByPrimaryKey(id);
        if(StringUtil.isEmpty(permission)) {
            throw new BizException(ResponseCode.PARAM_ILLEGAL_ERROR, "权限不存在");
        }
        if(1 == permission.getStatus()) {
            throw new BizException(ResponseCode.PARAM_ILLEGAL_ERROR, "权限状态错误");
        }
        permission.setStatus(1);
        permissionDAO.updateByPrimaryKey(permission);
    }

    /**
     * 停用
     * @param id
     */
    @Transactional(rollbackFor = {Exception.class}, isolation = Isolation.READ_COMMITTED)
    public void cancel(Long id) {
        //查询权限是否存在
        Permission permission = permissionDAO.selectByPrimaryKey(id);
        if(StringUtil.isEmpty(permission)) {
            throw new BizException(ResponseCode.PARAM_ILLEGAL_ERROR, "权限不存在");
        }
        if(2 == permission.getStatus()) {
            throw new BizException(ResponseCode.PARAM_ILLEGAL_ERROR, "权限状态错误");
        }
        permission.setStatus(2);
        permissionDAO.updateByPrimaryKey(permission);
    }

    /**
     * 删除
     * @param id
     */
    @Transactional(rollbackFor = {Exception.class}, isolation = Isolation.READ_COMMITTED)
    public void delete(Long id) {
        //查询权限是否存在
        Permission permission = permissionDAO.selectByPrimaryKey(id);
        if(StringUtil.isEmpty(permission)) {
            throw new BizException(ResponseCode.PARAM_ILLEGAL_ERROR, "权限不存在");
        }
        if(1 == permission.getStatus()) {
            throw new BizException(ResponseCode.PARAM_ILLEGAL_ERROR, "权限状态错误");
        }
//        permission.setStatus(3);
//        permissionDAO.updateByPrimaryKey(permission);
        permissionDAO.deleteByPrimaryKey(permission.getId());
    }

    /**
     * 查询权限详情
     * @param id
     * @return
     */
    public Permission detail(Long id) {
        //查询权限是否存在
        Permission permission = permissionDAO.selectByPrimaryKey(id);
        if(StringUtil.isEmpty(permission)) {
            throw new BizException(ResponseCode.PARAM_ILLEGAL_ERROR, "权限不存在");
        }
        return permission;
    }

}
